package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ciei.dpagm.entity.*;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.DateUtil;
import com.ciei.dpagm.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kiho
 * @date 2023/09/15
 */
@Service
public class HomePageService {

    @Autowired
    private ChipService chipService;
    @Autowired
    private DriverLibraryService driverLibraryService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectMasterChipConfigService projectMasterChipConfigService;
    @Autowired
    private ProjectSlaveChipConfigService projectSlaveChipConfigService;

    /**
     * 统计芯片库分布情况
     *
     * @param data 芯片类型  1：主控芯片 2：被控芯片
     * @return 按芯片分类统计的芯片个数
     */
    public JSONObject countChipDistribution(JSONObject data) {
        JSONArray chipCategoryCountArray = new JSONArray();
        // 芯片类型  1：主控芯片 2：被控芯片
        Integer chipType = null;
        if (data != null) {
            chipType = data.getInteger("chipType");
        }
        LambdaQueryWrapper<Chip> chipWrapper = new LambdaQueryWrapper<>();
        chipWrapper.select(Chip::getChipId,Chip::getDisplayCategory)
                .eq(chipType != null, Chip::getType, chipType);
        // <displayCategory,总数>
        Map<String, Long> chipCategoryCountMap = new HashMap<>();
        List<Chip> chipList = chipService.list(chipWrapper);
        if (chipList != null && !chipList.isEmpty()) {
            chipCategoryCountMap = chipList.stream().collect(Collectors.groupingBy(Chip::getDisplayCategory, Collectors.counting()));
        }
        if (!chipCategoryCountMap.isEmpty()) {
            chipCategoryCountMap.forEach((displayCategory, count) -> {
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("name", displayCategory);
                itemMap.put("value", count);
                chipCategoryCountArray.add(itemMap);
            });
        }
        return JsonUtil.getSuccess("").fluentPut(APP.DATA, chipCategoryCountArray);
    }

    /**
     * 统计驱动库分布情况
     *
     * @param data 驱动库类型  1：主控 2：被控
     * @return 按芯片分类统计的驱动库个数
     */
    public JSONObject countDriverDistribution(JSONObject data) {
        JSONArray driverCategoryCountArray = new JSONArray();
        // 驱动库类型  1：主控 2：被控
        Integer driverType = null;
        if (data != null) {
            driverType = data.getInteger("driverType");
        }
        LambdaQueryWrapper<Chip> chipWrapper = new LambdaQueryWrapper<>();
        chipWrapper.select(Chip::getChipId,Chip::getDisplayCategory);
        List<Chip> chipList = chipService.list(chipWrapper);
        // <displayCategory,芯片ID列表>
        Map<String, List<Integer>> categoryMap = chipList.stream()
                .collect(Collectors.groupingBy(Chip::getDisplayCategory, Collectors.mapping(Chip::getChipId, Collectors.toList())));

        LambdaQueryWrapper<DriverLibrary> driverWrapper = new LambdaQueryWrapper<>();
        driverWrapper.eq(driverType != null, DriverLibrary::getType, driverType);
        List<DriverLibrary> driverList = driverLibraryService.list(driverWrapper);
        if (driverList != null && !driverList.isEmpty()) {
            categoryMap.forEach((displayCategory, chipIdList) -> {
                long driverCategoryCount = driverList.stream().filter(driver -> chipIdList.contains(driver.getChipId())).count();
                if (driverCategoryCount != 0) {
                    Map<String, Object> itemMap = new HashMap<>();
                    itemMap.put("name", displayCategory);
                    itemMap.put("value", driverCategoryCount);
                    driverCategoryCountArray.add(itemMap);
                }
            });
        }
        return JsonUtil.getSuccess("").fluentPut(APP.DATA, driverCategoryCountArray);
    }

    /**
     * 按月份分组统计项目数量
     *
     * @param data
     * @return
     */
    public JSONObject countProjectDistribution(JSONObject data) {
        JSONObject result = new JSONObject();
        List<String> createTimeList = new ArrayList<>();
        List<Long> projectCountList = new ArrayList<>();

        Calendar startMonthCal = Calendar.getInstance();
        Calendar endMonthCal = Calendar.getInstance();
        // 开始月份 [yyyy-MM]
        String startMonth = null;
        // 结束月份 [yyyy-MM]
        String endMonth = null;
        if (data != null) {
            startMonth = data.getString("startMonth");
            endMonth = data.getString("endMonth");
        }
        // 计算开始时间和结束时间
        if (StringUtils.isNoneBlank(startMonth, endMonth)) {
            Date startMonthDate = DateUtil.stringToDate(startMonth, DateUtil.FORMAT_MONTH);
            if (startMonthDate != null) {
                startMonthCal.setTime(startMonthDate);
                DateUtil.setFirstDayZeroTimeOfMonth(startMonthCal);
            }
            Date endMonthDate = DateUtil.stringToDate(endMonth, DateUtil.FORMAT_MONTH);
            if (endMonthDate != null) {
                endMonthCal.setTime(endMonthDate);
                DateUtil.setFirstDayZeroTimeOfMonth(endMonthCal);
            }
        } else {
            startMonthCal.add(Calendar.MONTH, -5);
            DateUtil.setFirstDayZeroTimeOfMonth(startMonthCal);
            DateUtil.setFirstDayZeroTimeOfMonth(endMonthCal);
        }
        endMonthCal.add(Calendar.MONTH, 1);

        // 查询时间范围内的项目
        LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<>();
        projectWrapper.select(Project::getProjectId, Project::getCreateTime)
                .ge(Project::getCreateTime, startMonthCal.getTime())
                .lt(Project::getCreateTime, endMonthCal.getTime());
        List<Project> projectList = projectService.list(projectWrapper);

        // 得到时间数组（yyyy-MM）
        while (startMonthCal.compareTo(endMonthCal) < 0) {
            createTimeList.add(startMonthCal.get(Calendar.YEAR)
                    + "-"
                    + StringUtils.leftPad(String.valueOf(startMonthCal.get(Calendar.MONTH) + 1), 2, '0'));
            startMonthCal.add(Calendar.MONTH, 1);
        }

        // 按时间分组统计项目数量
        if (projectList != null && !projectList.isEmpty()) {
            createTimeList.forEach(createTime -> {
                long projectCount = projectList.stream()
                        .filter(project -> createTime.equals(DateUtil.dateToString(project.getCreateTime(), DateUtil.FORMAT_MONTH)))
                        .count();
                projectCountList.add(projectCount);
            });
        }

        result.fluentPut("createTime", createTimeList)
                .fluentPut("projectCount", projectCountList);
        return JsonUtil.getSuccess("").fluentPut(APP.DATA, result);
    }

    /**
     * 芯片使用情况分析
     *
     * @param data
     * @return
     */
    public JSONObject countChipUsage(JSONObject data) {
        JSONObject result = new JSONObject();
        List<String> modelList = new ArrayList<>();
        List<Long> projectCountList = new ArrayList<>();

        LambdaQueryWrapper<Chip> chipWrapper = new LambdaQueryWrapper<>();
        chipWrapper.select(Chip::getChipId, Chip::getModel);
        List<Chip> chipList = chipService.list(chipWrapper);

        LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<>();
        projectWrapper.select(Project::getProjectId);
        List<Project> projectList = projectService.list(projectWrapper);

        List<ProjectMasterChipConfig> projectMasterChipConfigList = projectMasterChipConfigService.list();
        List<ProjectSlaveChipConfig> projectSlaveChipConfigList = projectSlaveChipConfigService.list();

        Map<String, Long> modelProjectCountMap = new HashMap<>();
        chipList.forEach(chip -> {
            long masterChipUsageCount = projectMasterChipConfigList.stream()
                    .filter(config -> chip.getChipId().equals(config.getChipId()))
                    .map(ProjectMasterChipConfig::getProjectId)
                    .filter(projectId -> projectList.stream().anyMatch(project -> project.getProjectId().equals(projectId)))
                    .distinct()
                    .count();
            long slaveChipUsageCount = projectSlaveChipConfigList.stream()
                    .filter(config -> chip.getChipId().equals(config.getChipId()))
                    .map(ProjectSlaveChipConfig::getProjectId)
                    .filter(projectId -> projectList.stream().anyMatch(project -> project.getProjectId().equals(projectId)))
                    .distinct()
                    .count();
            modelProjectCountMap.put(chip.getModel(), masterChipUsageCount + slaveChipUsageCount);
        });

        // 排序
        List<Map.Entry<String,Long>> list = new ArrayList<>(modelProjectCountMap.entrySet());
        list.sort((o1, o2) -> (int) (o2.getValue() - o1.getValue()));

        if (data != null) {
            // 筛选前几名
            Integer top = data.getInteger("top");
            if (top != null && top > 0) {
                list = list.subList(0, top);
            }
        }

        list.forEach(entry->{
            modelList.add(entry.getKey());
            projectCountList.add(entry.getValue());
        });

        result.fluentPut("model", modelList)
                .fluentPut("projectCount", projectCountList);
        return JsonUtil.getSuccess("").fluentPut(APP.DATA, result);
    }
}
